package utils;

import java.io.Serializable;
import net.sf.navigator.menu.MenuComponent;
import net.sf.navigator.menu.PermissionsAdapter;
import domain.UserAccount;

/**
 * struts-menu的权限相关的控制器,根据用户权限来控制菜单可见-不可见.
 * @author zhuweiguo
 */
public class MenuPermissionAdapter implements PermissionsAdapter, Serializable {
    /**
     * serialVersionUID.
     */
    private static final long serialVersionUID = -6360659958364616969L;

    /**
     * 当前登陆的用户.
     */
    private final UserAccount curUser;

    /**
     * Creates a new instance of MenuPermissionAdapter.
     * @param pCurUser 当前登陆用户
     */
    public MenuPermissionAdapter(UserAccount pCurUser) {
        super();
        this.curUser = pCurUser;
    }

    /**
     * 确定该菜单是否是当前用户可以访问的菜单.
     * @param menu 菜单
     * @return boolean
     */
    public boolean isAllowed(MenuComponent menu) {
        if (menu.getRoles() == null) {
            // no roles define, allow everyone
            return true;
        } else {
            // Get the list of roles this menu allows
            String[] allowedRoles = menu.getRoles().split(",");
            // Get current User in session
            for (String allowedRole : allowedRoles) {
                if (allowedRole.equals(curUser.getRoleID())) {
                    return true;
                }
            }
        }
        return false;
    }

}
